﻿#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.dll"
#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.Runtime.dll"

#load "Client.fs"

open Client
open Microsoft.SharePoint.Client
open Microsoft.SharePoint.Client.Application
open System.Security;

// =======================================================
// Break role inheritance and assign new roles for users
// =======================================================

let list = Client.Context.Web.Lists.GetByTitle("Documents")
Client.Load list

let item = list.GetItemById(1)
Client.Load item

item.BreakRoleInheritance(true, false)
Client.ExecuteQuery()

Client.Load item.RoleAssignments

// Check if someone has read permissions
for ra in item.RoleAssignments do
    Client.Load ra.RoleDefinitionBindings
    Client.Load ra.Member
    let mutable readExists = false
    for role in ra.RoleDefinitionBindings do
        Client.Load role
        if role.Name = "Read" then
            readExists <- true
            let msg = "Read exists for " + ra.Member.LoginName
            printfn "%s\n" msg



// Breaking the security inheritance of a document and adding a user as reader
item.BreakRoleInheritance(false, true)

let spUser = Client.Context.Web.SiteUsers.GetByLoginName("")
let oRoleDefinition = Client.Context.Web.RoleDefinitions.GetByType(RoleType.Reader)

let collRoleDefinitionBinding = new RoleDefinitionBindingCollection(Client.Context);
collRoleDefinitionBinding.Add(oRoleDefinition);
let oRoleAssignment = item.RoleAssignments.Add(spUser, collRoleDefinitionBinding);
Client.ExecuteQuery()
